package org.victoria.market.dao;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.victoria.market.utils.QueryHelper;
import java.util.List;

/**
 * Created by Administrator on 2014/12/21.
 */
@Component
@SuppressWarnings("unchecked")
public class DaoSupport{

    @Autowired private SqlSessionFactory sessionFactory;
    private QueryHelper helper;
    private SqlSession session;

    private SqlSession getSession(){
        if (session==null)
            session = sessionFactory.openSession();
        return session;
    }

    public QueryHelper getQueryHelper(){
        if (helper==null)
            helper = new QueryHelper(this);
        return helper;
    }

    public QueryHelper openQueryHelper(){
        helper = new QueryHelper(this);
        session = sessionFactory.openSession();
        return helper;
    }

    public int save() {
        return getSession().insert(helper.getNamespace(), helper.getValue());
    }

    public <E> E findOne() {
        if (helper.hasValue()){
            return this.getSession().selectOne(helper.getNamespace(), helper.getValue());
        }else{
            return this.getSession().selectOne(helper.getNamespace());
        }
    }

    public <E> List<E> find() {
        if (helper.hasValue()){
            return this.getSession().selectList(helper.getNamespace(), helper.getValue());
        }else{
            return this.getSession().selectList(helper.getNamespace());
        }
    }

    public int deleteOne() {
        if (helper.hasValue()){
            return this.getSession().delete(helper.getNamespace(), helper.getValue());
        }else {
            return this.getSession().delete(helper.getNamespace());
        }
    }

    public int getCount() {
        if (helper.hasValue()){
            return this.getSession().selectOne(helper.getNamespace(), helper.getValue());
        }else{
            return this.getSession().selectOne(helper.getNamespace());
        }
    }

    public int updateOne() {
        if (helper.hasValue()){
            return this.getSession().update(helper.getNamespace(), helper.getValue());
        }else {
            return this.getSession().update(helper.getNamespace());
        }
    }
}
